define(['bootstrapTable', 'layer'], function (bootstrapTable, layer) {
    return {
        initList: function () {
            dataList();
            submitCallRecords()
            /*检索*/
            $("#search").click(function () {
                $('#alarmEnterAreaTable').bootstrapTable("refresh");
            })
        },
        initEdit: function () {
            if ($("#id").val() != "") {
                $('.up-map-div').addClass('hidden-gew');
            }else{
                $('.up-map-div').removeClass('hidden-gew');
            }
            load();
            /**检索位置*/
            $("#search").click(function () {
                // map.clearOverlays()
                //查询中心点
                if ($("#name").val().trim() != "") {
                    local.search($("#name").val());
                    local.setSearchCompleteCallback(function (rs) {
                        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                            //搜索之后设置地图中心点
                            map.panTo(rs.getPoi(0).point);
                            //按照设置米数调整层级
                            if (marker) {
                                marker.setPosition(rs.getPoi(0).point)
                            } else {
                                marker = new BMap.Marker(rs.getPoi(0).point, {
                                    icon: new BMap.Icon("/images/icon/biaoji.png", new BMap.Size(24, 24))
                                });
                                marker.enableDragging()
                                map.addOverlay(marker);
                            }

                        }
                    });
                }
                else {
                    layer.msg("请输入指定地点");
                }
            })
            /**设置范围*/
            $("#setRange").on('click', function () {
                if (marker) {
                    if (circle) {
                        circle.setCenter(marker.getPosition())
                        circle.setRadius($("#range").val())
                    } else {
                        circle = new BMap.Circle(marker.getPosition(), $("#range").val(), {
                            fillColor: "blue",
                            strokeWeight: 1,
                            fillOpacity: 0.3,
                            strokeOpacity: 0.3
                        });
                        circle.enableEditing();
                        circle.addEventListener("lineupdate", function (type) {
                            var v = map.getViewport(type.target.getPath());//通过坐标数据得到中心点
                            map.centerAndZoom(v.center, v.zoom);//
                        })
                        circle.addEventListener("click", function (type) {
                            console.log(type.target.getPath());
                            layer.prompt({title: '输入指定地点名称，并确认', formType: 2}, function (text, index) {
                                var center = marker.getPosition().lng + "," + marker.getPosition().lat
                                submitData = {
                                    "geo": JSON.stringify(type.target.getPath()),
                                    "range": $('#range').val(),//范围
                                    "name": text,//地点名称
                                    "center": center,
                                    "lv": map.getZoom()
                                };
                                $.ajax({
                                    url: "/alarmEnterAreaController/add",
                                    dataType: "json",
                                    type: "post",
                                    data: submitData,
                                    success: function (result) {
                                        layer.confirm('指定地点保存成功!，是否继续添加？', {
                                            btn: ['添加', '返回'] //按钮
                                        }, function () {
                                            layer.closeAll();
                                            window.location.reload()
                                        }, function () {
                                            layer.closeAll();
                                            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                                            parent.layer.close(index);
                                            parent.$('#alarmEnterAreaTable').bootstrapTable('refresh')

                                        });
                                    }
                                })
                            });

                        })
                        map.addOverlay(circle);
                    }
                }
                else {
                    layer.msg("未设置指定地点");
                }
            })
        }
    };
    /**列表数据绑定*/
    function dataList() {
        window.openEvent = {
            //删除行
            'click .showInfo': function (e, value, row, index) {
                $(this).blur();
                layer.open({
                    type: 2,
                    title: "查看",
                    anim: 1,
                    closeBtn: 1,
                    area: ['80%', '80%'],
                    content: '/alarmEnterAreaController/goEdit?id=' + row.id
                });
            },
            //删除行
            'click .delete': function (e, value, row, index) {
                layer.confirm('确定要删除选中记录吗 ？', {
                    icon: 3,
                    btn: ['确定', '取消']
                }, function (index, layero) {
                    $.ajax({
                        url: '/alarmEnterAreaController/delByIds',
                        type: "post",
                        data: "ids=" + row.id,
                        dataType: "JSON",
                        success: function (data) {
                            if (data.code == 10001) {
                                layer.msg(data.msg, {
                                    icon: 1,
                                    time: 1000
                                });
                                $('#alarmEnterAreaTable').bootstrapTable('refresh')
                            }
                            layer.msg(data.msg);
                        }
                    });
                });
            }
        }
        $('#alarmEnterAreaTable').bootstrapTable({
            url: "/alarmEnterAreaController/pageSelect", // 获取表格数据的url
            method: 'post',
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            contentType: 'application/x-www-form-urlencoded',
            sidePagination: 'server', // 设置为服务器端分页，必要
            queryParamsType: "",
            queryParams: function (params) {
                return tem = {
                    rows: params.pageSize,
                    page: params.pageNumber,
                    myPhone: $("#searchPhone").val()
                }
            },
            clickToSelect: false,
            columns: [
                {
                    title: '序号',
                    align: 'center',
                    formatter: showNumber,
                    width: '1%'
                }, {
                    field: 'ck',
                    checkbox: true,
                    align: 'center',
                    valign: 'middle',
                    width: '1%'
                },
                {
                    field: 'name',
                    title: '指定地点名称',
                    align: 'center',
                    valign: 'middle',
                    width: '16%'

                }, {
                    field: 'range',
                    title: '范围',
                    align: 'center',
                    valign: 'middle',
                    width: '16%'
                }
                , {
                    field: 'operator',
                    title: "操作",
                    align: 'center',
                    valign: 'middle',
                    width: '10%',
                    events: openEvent,
                    formatter: function (value, row, index) {
                        return ['<button class="btn btn-xs btn-info btn-operator-gew showInfo"><i class="fa fa-map-marker"></i>查看</button>', '<button class="btn btn-xs btn-danger delete"><i class="fa fa-trash-o"></i>删除</button>'].join("");
                    }
                }
            ],
            onLoadSuccess: function (data) {  //加载成功时执行

            },
            onLoadError: function () {  //加载失败时执行
                //console.info("加载数据失败");
            }
        });
    }
    /**添加或编辑**/
    var map;//地图
    var local;
    var circle;//范围
    var marker;//中心点
    /**初始化加载地图*/
    function load() {
        map = new BMap.Map("mapDiv"); //初始化地图
        map.enableScrollWheelZoom();//启动滚动缩进
        //查看设置
        if ($("#id").val() != "") {
            //通过后台返回数据进行地图展现
            $.ajax({
                url: "/alarmEnterAreaController/findById",
                dataType: "json",
                type: "post",
                async: false,
                data: {
                    'id': $("#id").val()
                },
                success: function (result) {
                    var data = result.data;
                    var point = data.center.split(',');
                    var point = new BMap.Point(point[0], point[1]); //设置地图中心点
                    map.centerAndZoom(point, data.lv);
                    //查看时添加标注
                    marker = new BMap.Marker(point, {
                        icon: new BMap.Icon("/images/icon/biaoji.png", new BMap.Size(24, 24))
                    });
                    map.addOverlay(marker);
//查看时绘制范围
                    polygon = new BMap.Polygon(data.boundary, {
                        fillColor: "blue",
                        strokeWeight: 1,
                        fillOpacity: 0.3,
                        strokeOpacity: 0.3
                    });
                    map.addOverlay(polygon);
                }
            })
        } else {//添加
            var point = new BMap.Point(106.63543, 26.651516); //设置地图中心点
            map.centerAndZoom(point, 13);
            var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
            var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
            map.addControl(top_left_control);      // 测距离的
            map.addControl(top_left_navigation);   // 左导航默认
            local = new BMap.LocalSearch(map, {forceLocal: true});
        }
    }
    /** 添加*/
    function submitCallRecords() {
        $('.addBtn').on('click', function () {
            $(this).blur();
            layer.open({
                type: 2,
                title: "新增",
                anim: 1,
                closeBtn: 1,
                area: ['80%', '80%'],
                content: '/alarmEnterAreaController/goEdit?id='
            });
        });
    }
    function showNumber(value, row, index) {
        var options = $('#alarmEnterAreaTable').bootstrapTable('getOptions');
        return options.pageSize * (options.pageNumber - 1) + index + 1;
    }
})